<script setup lang="tsx">
import { iconToSVG, svgToData, svgToURL } from '@iconify/utils';
import { h, nextTick, onMounted, ref, VNode } from 'vue';
import { Icon, getIcon } from '@iconify/vue';
import { GetIcons, SetIcons } from "../../../wailsjs/go/main/App";
import { collections as allIconCollections } from '@iconify-collections';
import { NInput, NTabs, NTabPane, NColorPicker, NLayout, NLayoutSider, NLayoutContent, NLayoutFooter, NLayoutHeader, NSelect, NInputGroup, NButton, SelectOption, useMessage } from 'naive-ui'
import { useToolsStore } from '@/stores/tools';

const toolsStore = useToolsStore();

const collections = ref<Array<{ prefix: string, name: string, total?: number }>>([]);
const selectedCollection = ref<string>('');
const iconsInCollection = ref<string[]>([]);
const loading = ref(false);
const iconPreviewSize = '64px'; // Size for preview icons
const searchTerm = ref("")
const searchKey = ref("")
const currentIcon = ref("")
const allNumber = ref(0)
const allIcons = ref([])
const myIcons = ref([])
const page = ref(1)
const iconColor = ref("#000000")
let size = 120;
let count = 0
let iconStringIndex = 0
let iconName = ""
const iconOptions = ref([])
const iconValue = ref("")
const iconIcon = ref("")
const iconSVG = ref("")
const message = useMessage()
const refIconPreview = ref()
const iconColors = [
  "#000000",   // 纯黑
  "#333333",   // 深灰
  "#666666",   // 中灰
  "#999999",   // 浅灰
  "#CCCCCC",   // 淡灰
  "#F5F5F5",   // 近白灰
  "#FFFFFF",   // 纯白
  "#165DFF",   // 深蓝
  "#4E6EF2",   // 中蓝
  "#86A1FF",   // 浅蓝
  "#00B42A",   // 深绿
  "#0FC672",   // 中绿
  "#71DD37",   // 浅绿
  "#F53F3F",   // 深红
  "#FF672B",   // 橙红
  "#FF7D00"    // 橙黄
];

onMounted(() => {
  try {
    // 从预处理的数据中读取所有图标集
    collections.value = allIconCollections.sort((a, b) => a.id.localeCompare(b.id));
    allNumber.value = collections.value.reduce((acc, cur) => acc + (cur.total || 0), 0)
    // 确保正确地将所有图标集的icons字段合并到allIcons中
    let all = []
    collections.value.forEach(c => {
      if (c.icons) {
        c.icons.forEach(i => {
          all.push({
            prefix: c.id,
            name: i
          })
        })
      }
    })
    allIcons.value = all
    console.log('allIcons', allIcons.value.length)
    //读取我的图标
    getMyIcons()
  } catch (error) {
    console.error('Error initializing icon collections:', error);
  }
});

async function getMyIcons() {
  let res = ''
  if (window.runtime) {
    res = await GetIcons()
  } else {
    console.log('wails error')
    res = toolsStore.myIcons

  }
  const iconList = res.split(',')?.filter(i => i != '') || []
  let myAll = []
  iconList.forEach(i => {
    const a = i.split(':')
    myAll.push({
      prefix: a[0],
      name: a[1]
    })
    myIcons.value = myAll
    console.log('myIconList', myIcons.value)
  })
}

async function addMyIcon(icon: string) {
      myIcons.value.push(icon)
      if (window.runtime) {
        await SetIcons(myIcons.value.join(','))
      } else {
        let saveMyIcons = toolsStore.myIcons
        if (saveMyIcons.indexOf(icon) == -1) {
          saveMyIcons += icon + ','
          toolsStore.myIcons = saveMyIcons
        }

      }

    }

// 加载集合中的图标
const loadIconsInCollection = (prefix: string) => {
    console.log('loadIconsInCollection', prefix)
    selectedCollection.value = prefix;
    iconsInCollection.value = [];
    loading.value = true;
    page.value = 1
    try {
      // 对于每个集合，我们尝试加载一些常见的图标
      // 这比尝试加载整个集合更高效且适合浏览器环境
      if (prefix === 'all') {
        iconsInCollection.value = allIcons.value
        if (searchTerm.value != '') {
          count = allIcons.value.filter(i => i.name.includes(searchTerm.value)).length
          iconsInCollection.value = allIcons.value.filter(i => i.name.includes(searchTerm.value)).slice(0, page.value * size)
        } else {
          count = allIcons.value.length
          iconsInCollection.value = allIcons.value.slice(0, page.value * size)
        }
      } else if (prefix === 'my') {
        iconsInCollection.value = myIcons.value
        if (searchTerm.value != '') {
          count = myIcons.value.filter(i => i.name.includes(searchTerm.value)).length
          iconsInCollection.value = myIcons.value.filter(i => i.name.includes(searchTerm.value)).slice(0, page.value * size)
        } else {
          count = myIcons.value.length
          iconsInCollection.value = myIcons.value.slice(0, page.value * size)
        }
      } else {
        iconsInCollection.value = collections.value.find(c => c.id === prefix)?.icons || [];
        if (searchTerm.value != '') {
          iconsInCollection.value = iconsInCollection.value.filter(i => i.includes(searchTerm.value))
        }
        count = iconsInCollection.value.length
      }
      console.log(`Loaded ${iconsInCollection.value.length} icons in ${prefix}`);

    } catch (error) {
      console.error(`Error loading icons for collection ${prefix}:`, error);
      iconsInCollection.value = [];
    } finally {
      loading.value = false;
    }
  };

  function searchIcons() {
    searchTerm.value = searchKey.value
    if (!selectedCollection.value) {
      selectedCollection.value = 'all'
    }
    loadIconsInCollection(selectedCollection.value)

  }

  function handleSearchKeyUp(e) {
    if (e.code === 'Enter') {
      searchIcons()
    }
  }

  // 加载更多图标
  const loadMoreIcons = () => {
    console.log('loadMoreIcons')
    page.value++;
    if (selectedCollection.value === 'all') {
      if (searchTerm.value != '') {
        iconsInCollection.value = allIcons.value.filter(i => i.name.includes(searchTerm.value)).slice(0, page.value * size)
      } else {
        iconsInCollection.value = allIcons.value.slice(0, page.value * size)
      }
    }
  };

  function onSelectIcon(icon: string) {
    currentIcon.value = icon
    const icons = icon.split(':')
    let options = [
      {
        label: icon,
        value: icon,
        type: 'iconify'
      },
      {
        label: 'iconify ' + icons[0] + "--" + icons[1],
        value: 'iconify ' + icons[0] + "--" + icons[1],
        type: 'Tailwind CSS'
      },
      {
        label: 'icon-[' + icons[0] + "--" + icons[1] + ']',
        value: 'icon-[' + icons[0] + "--" + icons[1] + ']',
        type: 'Tailwind CSS: dynamic'
      },
      {
        label: 'i-' + icon,
        value: 'i-' + icon,
        type: 'UnoCSS'
      },
      {
        label: 'i-' + icons[0] + "-" + icons[1],
        value: 'i-' + icons[0] + "-" + icons[1],
        type: 'UnoCSS'
      }
    ]

    iconOptions.value = options
    iconName = icon
    iconValue.value = options[iconStringIndex].value


    iconIcon.value = `<Icon icon="${icon}" style="color: ${iconColor.value}" />`
    renderIconPreview()
  }

  function updateIconColor(color) {
    iconColor.value = color
    iconIcon.value = `<Icon icon="${iconValue.value}" style="color: ${iconColor.value}" />`
    renderIconPreview()
  }


  // 修改renderIconPreview函数以正确处理iconSVG
  function renderIconPreview() {
    nextTick(() => {
      try {
        const icons = iconValue.value.split(':');

        if (icons.length < 2) {
          console.error('Invalid icon format:', iconValue.value);
          iconSVG.value = 'Invalid icon format';
          return;
        }

        // 从@iconify/json获取图标数据
        const iconData = getIcon(iconName);

        if (!iconData) {
          console.error('Icon not found:', iconValue.value);
          iconSVG.value = 'Icon not found';
          return;
        }

        // 使用iconToSVG处理图标数据
        const svgData = iconToSVG(iconData, {
          color: iconColor.value // 应用图标颜色
        });

        // 构建完整的SVG字符串
        const svgString = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${svgData.width} ${svgData.height}" fill="currentColor" style="color: ${iconColor.value}">
  ${svgData.body}
</svg>`;

        iconSVG.value = svgString;
      } catch (error) {
        console.error('Error rendering icon preview:', error);
        iconSVG.value = 'Error rendering SVG';
      }
    });
  }

  // 修复renderOption函数，确保option内容正确显示
  // 修复renderOption函数，确保保留原有的node结构和事件监听器
  function renderOption({ node, option }: { node: VNode, option: SelectOption }) {
    // 正确的做法是修改node的子节点，而不是创建一个全新的元素

    const label = h('div', {
      class: 'flex items-center'
    }, [
      h('div', {
        class: 'mr-2'
      }, option.label),
      h('div', {
        class: 'text-xs text-gray-600'
      }, "(" + option.type + ")")
    ]);

    node.children[0].children[0] = label;
    return node;
  }

  function copyIconName() {
    if (iconValue.value) {
      navigator.clipboard.writeText(iconValue.value).then(() => {
        message.success('图标名称已复制');
      });
    }
  }

  function updateIconValue(value) {
    console.log('updateIconValue', value)
    iconStringIndex = iconOptions.value.findIndex(i => i.value === value)
    console.log('updateIconValue', iconStringIndex)
    iconValue.value = value
    iconIcon.value = `<Icon icon="${iconValue.value}" style="color: ${iconColor.value}" />`
    renderIconPreview()
  }
</script>

<template>
  <n-layout has-sider class="h-full overflow-hidden">
    <n-layout-sider bordered content-style="padding: 24px;" width="260px">
      <div class="w-200px h-full flex flex-col overflow-hidden">
        <div class="accent-coolGray overflow-hidden sticky top-0 bg-white z-10 p-2 -mx-2">
          <div class="border p-3 rounded-lg hover:bg-gray-50  cursor-pointer mb-4"
            :class="{ 'border-green-500 bg-green-50': selectedCollection === 'my' }"
            @click="loadIconsInCollection('my')">
            <div class="flex items-center justify-between">
              <div class="font-medium">我的收藏</div>
              <Icon v-if="selectedCollection === 'my'" icon="ph:check" style="width: 24px; height: 24px;"
                class="text-green-500 bg-white" :width="16" :height="16" />
            </div>
            <div class="text-xs text-gray-600 mb-1">我收藏的图标</div>
            <div class="text-xs text-blue-600">
              {{ myIcons.length }} 个图标
            </div>
          </div>
          <div class="border p-3 rounded-lg hover:bg-gray-50  cursor-pointer mb-4"
            :class="{ 'border-green-500 bg-green-50': selectedCollection === 'all' }"
            @click="loadIconsInCollection('all')">
            <div class="flex items-center justify-between">
              <div class="font-medium">所有图标集</div>
              <Icon v-if="selectedCollection === 'all'" icon="ph:check" style="width: 24px; height: 24px;"
                class="text-green-500 bg-white" :width="16" :height="16" />
            </div>
            <div class="text-xs text-gray-600 mb-1"> {{ collections.length }} 个图标集</div>
            <div class="text-xs text-blue-600">
              {{searchTerm === '' ? allNumber : (allIcons.filter(icon =>
                icon.name?.toLowerCase().includes(searchTerm.toLowerCase())).length || 0)}} 个图标
            </div>
          </div>

        </div>
        <!-- Collection Selection -->
        <div class="grid grid-cols-1 flex-1 gap-3 mb-6  overflow-y-auto">
          <div v-for="item in collections" :key="item.id" class="border p-3 rounded-lg hover:bg-gray-50  cursor-pointer"
            :class="{ 'border-green-500 bg-green-50': selectedCollection === item.id }"
            @click="loadIconsInCollection(item.id)">
            <div class="flex items-center justify-between">
              <div class="font-medium">{{ item.id }}</div>
              <Icon v-if="selectedCollection === item.id" icon="ph:check" style="width: 24px; height: 24px;"
                class="text-green-500 bg-white" :width="16" :height="16" />
            </div>
            <div class="text-xs text-gray-600 mb-1">{{ item.name }}</div>
            <div class="text-xs text-blue-600">
              {{searchTerm === '' ? item.total?.toLocaleString() : (item.icons?.filter(icon =>
                icon.toLowerCase().includes(searchTerm.toLowerCase())).length || 0)}} 个图标

            </div>
          </div>
        </div>

      </div>
    </n-layout-sider>
    <n-layout content-class="h-full overflow-hidden flex flex-col">
      <n-layout-header bordered>
        <div class="flex items-center p-2">
          <h3 class="text-lg font-semibold mb-3">
            {{ selectedCollection }} 图标
            <span v-if="loading" class="text-sm font-normal text-gray-500">- 加载中...</span>
          </h3>
          <div class="relative w-full md:w-64 ml-auto">
            <n-input-group>
              <NInput type="text" v-model:value="searchKey" placeholder="搜索图标" clearable
                @clear="() => { searchKey = ''; searchIcons() }" @keyup="handleSearchKeyUp"
                class="focus:outline-none focus:ring-2 focus:ring-blue-500" />
              <n-button type="primary" ghost @click="searchIcons">
                搜索
              </n-button>
            </n-input-group>
          </div>
        </div>

      </n-layout-header>
      <n-layout-content content-style="padding: 24px;" content-class="flex-1 overflow-y-auto">
        <div v-if="selectedCollection" class="mt-8">
          <template v-if="iconsInCollection.length > 0">
            <div class="flex flex-wrap gap-3 p-3 bg-white  bg-gray-50 rounded-lg">
              <template v-for="(icon, index) in iconsInCollection" :key="icon">
                <template v-if="index < page * size">
                  <div
                    class="flex flex-col items-center gap-2 p-3 border rounded-lg w-100px h-100px cursor-pointer hover:shadow-md"
                    @click="onSelectIcon(selectedCollection + ':' + icon)"
                    v-if="selectedCollection != 'my' && selectedCollection != 'all'">
                    <Icon :icon="`${selectedCollection}:${icon}`" class="bg-white" :width="iconPreviewSize"
                      :height="iconPreviewSize" />
                  </div>
                  <div
                    class="flex flex-col items-center gap-2 p-3 border rounded-lg w-100px h-100px cursor-pointer hover:shadow-md"
                    @click="onSelectIcon(icon.prefix + ':' + icon.name)" v-else>
                    <Icon :icon="`${icon.prefix}:${icon.name}`" class="bg-white" :width="iconPreviewSize"
                      :height="iconPreviewSize" />
                  </div>

                </template>

              </template>

            </div>
            <div class="flex justify-center clear-both cursor-pointer text-primary" @click="loadMoreIcons"
              v-if="count > page * size">加载更多
            </div>
          </template>
          <div v-else-if="!loading" class="p-4 bg-gray-50 rounded-lg text-gray-500 text-center">
            No icons found or failed to load icons for this collection.
          </div>

        </div>
      </n-layout-content>
      <n-layout-footer bordered>
        <div class="mt-8 p-4 bg-blue-50 rounded-lg border border-blue-100 flex text-16px" v-if="currentIcon != ''">
          <div>
            <Icon ref="refIconPreview" class="bg-white" style="width:128px;height:128px;" :style="{ color: iconColor }"
              :icon="currentIcon" />
            <div class="flex justify-center cursor-pointer text-primary" @click="addMyIcon(currentIcon)">添加到收藏</div>
          </div>

          <div class="flex-1 ml-2 min-w-0">
            <div class="flex items-center text-16px">
              <NColorPicker style="width:28px" :swatches="iconColors" size="small" v-model:value="iconColor"
                @update:value="updateIconColor" :render-label="(color) => ''" />
              <div>图标名称：</div>
              <!-- 修复n-select组件的使用，确保正确传递属性 -->
              <n-select v-model:value="iconValue" :options="iconOptions" :render-option="renderOption"
                @update:value="updateIconValue" class="flex-1 min-w-0" placeholder="请选择图标" />
              <div class="ml-1" @click="copyIconName">
                <Icon style="width: 24px; height: 24px;" class="bg-white cursor-pointer" icon="icon-park-twotone:copy">
                </Icon>
              </div>
            </div>
            <n-tabs type="line" animated>
              <n-tab-pane name="Iconify" tab="Iconify">
                <p class="text-xs text-gray-600 mt-2">确认使用 '@iconify/vue' 的 Icon 组件</p>
                <pre class="text-sm text-gray-700 bg-white p-2 rounded overflow-auto">{{ iconIcon }}</pre>
              </n-tab-pane>
              <n-tab-pane name="SVG" tab="SVG">
                <pre class="text-sm text-gray-700 bg-white p-2 rounded overflow-x-auto">{{ iconSVG }}</pre>
              </n-tab-pane>
            </n-tabs>
          </div>
        </div>
      </n-layout-footer>
    </n-layout>
  </n-layout>

</template>
<style lang="less" scoped>
.iconify {
  width: 64px;
  height: 64px;
}
</style>